package br.com.uglyboys.persistence;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.util.Log;
import br.com.uglyboys.model.ObjetoRastreavel;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;

public class Persistencia {
	private static ObjectContainer oc = null;
	private Context context;

	public ObjectContainer db() {
		try {
			if (oc == null || oc.ext().isClosed()) {
				oc = Db4oEmbedded.openFile(dbConfig(), db4oDBFullPath(context));
			}
			return oc;
		} catch (Exception ie) {
			Log.e(Persistencia.class.getName(), ie.toString());
			return null;
		}
	}

	private EmbeddedConfiguration dbConfig() throws IOException {
		EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
		configuration.common().objectClass(ObjetoRastreavel.class).objectField("name").indexed(true);
		configuration.common().objectClass(ObjetoRastreavel.class).cascadeOnUpdate(true);
		configuration.common().objectClass(ObjetoRastreavel.class).cascadeOnActivate(true);
		return configuration;
	}

	private String db4oDBFullPath(Context ctx) {
		return context.getDir("data", 0) + "/" + "pumpup.db4o";
	}

	public Persistencia(Context ctx) {
		context = ctx;
	}

	public void salvarObjetoRastreavel(ObjetoRastreavel objetoRastreavel) {
		db().store(objetoRastreavel);
		db().commit();
	}

	public List<ObjetoRastreavel> getObjetosRastreaveis() {
		return db().query(ObjetoRastreavel.class);
	}

	public void removerObjetoRastreavel(ObjetoRastreavel objetoRastreavel) {
		db().delete(objetoRastreavel);
		db().commit();
	}

	public void atualizarObjetoRastreavel(ObjetoRastreavel objetoRastreavel) {
		db().store(objetoRastreavel);
		db().commit();
		
	}

}
